package io.renren.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {
    /**
     * get请求
     * @param url
     * @param params
     * @param cookieStore
     * @return
     * @throws Exception
     */
    public static String Get(String url, Map<String, String> params, CookieStore cookieStore) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);
        if(params != null) {
            params.forEach((k, v) -> {
                uriBuilder.setParameter(k,v);
            });
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        // 创建get方法的执行对象 HttpClient4.X之后是这样创建client对象的
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        HttpResponse response = client.execute(httpGet);
        String responseStr = EntityUtils.toString(response.getEntity(),"utf-8");


        return responseStr;
    }

    /**
     * post请求(用于key-value格式的参数)
     * @param url
     * @param params
     * @return
     */
    public static String Post(String url, Map params, CookieStore cookieStore) {

        BufferedReader in = null;
        try {
            // 定义HttpClient
            CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            // 实例化HTTP方法
            HttpPost request = new HttpPost(url);

            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if(params != null) {
                for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String value = String.valueOf(params.get(name));
                    nvps.add(new BasicNameValuePair(name, value));
                    //System.out.println(name +"-"+value);
                }
            }

            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {    //请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(), "utf-8" ));
                StringBuffer sb = new StringBuffer("" );
                String line = "";
                String NL = System.getProperty("line.separator" );
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }

                in.close();

                return sb.toString();
            } else {    //
                System.out.println("状态码：" + code);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

    public static String PostJson(String url, Map params, CookieStore cookieStore) {
        BufferedReader in = null;
        try {

//            HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
//            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

            // 定义HttpClient
            CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

            // 实例化HTTP方法
            HttpPost request = new HttpPost(url);
            if(params != null) {
                String str = JSON.toJSONString(params);
                StringEntity requestEntity = new StringEntity(str, "utf-8");
                requestEntity.setContentEncoding("UTF-8");
                request.setHeader("Content-type", "application/json");
                request.setEntity(requestEntity);
            }
            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {    //请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(), "utf-8" ));
                StringBuffer sb = new StringBuffer("" );
                String line = "";
                String NL = System.getProperty("line.separator" );
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }

                in.close();

                return sb.toString();
            } else {    //
                System.out.println("状态码：" + code);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }
}
